import { message } from 'antd';
import Schema from 'async-validator';
import { Model } from 'dva';
import { routerRedux } from 'dva/router';
import SurveyModelUtil from '../utils/Survey/SurveyModelUtil';
import { GaugeSurvey } from './../api';
import { IAllGauge } from './../assets/js/DataJson';
// import SHCZ20190001 from './../assets/js/SHCZ20190001';
message.config({
  top: 150,
});
// tslint:disable-next-line:no-any
let timer: any = null;
export interface ISurvey {
  gaugeData: IAllGauge[];
  menuIndex: number;
  menuIChild: number;
  doms: HTMLCollectionOf<Element> | [];
  answer: {
    // tslint:disable-next-line:no-any
    [key: string]: any;
  };
  countData: {
    // tslint:disable-next-line:no-any
    [key: string]: any;
  };
  // tslint:disable-next-line:no-any
  schema: { [key: string]: any };
  visitNumber: number;
  answerId: string;
  isCache: boolean;
  userId: undefined | number;
  channel: number;
  writeType: string; // 当前页面的填写方式
  currentCatchIf: boolean; // 当前页面是否需要缓存
  patientId: string;
  questionId: string;
  ossInfo: IOssInfo;
  code: string;
  roleType: 'patient' | 'doctor';
}
export interface IOssInfo {
  accessKeyId?: string;
  accessKeySecret?: string;
  expiration?: string;
  host?: string;
  securityToken?: string;
  bucket?: string;
}
export default {
  namespace: 'survey',
  state: {
    schema: {},
    gaugeData: [], // 所有量表数据
    menuIndex: -1, // 1级菜单下标
    menuIChild: -1, // 2级菜单下标
    answer: {}, // 答案
    countData: {}, // 算分使用
    currentAnswer: {}, // 当前访视的答案
    doms: [],
    visitNumber: 0, // 访视次数
    patientId: '', // 患者id
    answerId: '', // 问卷id
    isCache: false, // 是否缓存
    userId: undefined,
    channel: 0,
    writeType: '',
    currentCatchIf: false,
    questionId: '', // 新建问卷id
    ossInfo: {},
    code: '',
    roleAndUrl: '',
    roleType: 'doctor', // 填写人权限
  } as ISurvey,
  effects: {
    // 提交表单
    *submitFrom({ payload }, { call, put, select, take }) {
      const state = yield select(({ survey }: { survey: ISurvey }) => survey);
      const validator = new Schema(state.schema);
      const surveyModelUtil = new SurveyModelUtil();
      try {
        if (true) {
          yield validator.validate(state.answer);
        }

        delete state.answer.beforeModuleNames;

        const result = yield surveyModelUtil.submitSurvey({
          answerJson: JSON.stringify(state.answer),
          questionAnswerJson: JSON.stringify(state.gaugeData),
          writeType: state.writeType,
          id: state.answerId,
          visitNumber: state.answer.visitNumber,
          userId: state.userId,
          channel: state.channel,
          patientId: state.patientId,
          questionId: state.questionId,
          code: state.code,
        });

        yield put({ type: 'allSave', payload: { isCache: false } });
        message.info('提交成功');
        if (result.code) {
          yield put(
            routerRedux.replace(
              `/SubmitCase/${result.code}/${result.name}/${result.sampleSequence}?roleAndUrl=${state.roleAndUrl}`
            )
          );
          return;
        }
        window.history.back();
      } catch ({ errors }) {
        const gaugeData = yield surveyModelUtil.catchErrValidator(state.gaugeData, errors);
        yield put({ type: 'allSave', payload: { gaugeData: [...gaugeData], isCache: state.currentCatchIf } });
      }
    },
    /**
     * 初始化数据
     */
    *gaugeInit({ callback, payload }, { put, select }) {
      const surveyModelUtil = new SurveyModelUtil();
      // 判断是医生还是病人，再判断是否有资格填写
      const roleType = Boolean(payload && payload.code) ? 'patient' : 'doctor';
      // 获取答案之类的东西
      const { gaugeData, surveyInfo } = yield surveyModelUtil.getSurveyData(payload);
      const answerKey = surveyInfo.answerCacheJson ? 'answerCacheJson' : 'answerJson';
      const surveyAnswer = surveyInfo[answerKey] ? JSON.parse(surveyInfo[answerKey]) : {};
      payload.visitNumber = surveyInfo.visitNumber;
      // const CZ = new SHCZ20190001().gaugeStaticData;
      const surveyInitData = yield surveyModelUtil.surveyInit(
        JSON.parse(gaugeData.jsonDesc),
        // CZ,
        surveyAnswer,
        roleType,
        payload
      );
      // 访视要放到答案里，因为解析器是根据答案进行解析的
      surveyInitData.answer.visitNumber = surveyInfo.visitNumber;
      if (surveyInitData.answer.patient_sex === null || surveyInitData.answer.patient_sex === undefined) {
        surveyInitData.answer.patient_sex = surveyInfo.gender;
        surveyInitData.countData.patient_sex = surveyInfo.gender === '女' ? 0 : 1;
      }

      const { result } = yield GaugeSurvey.getToken();
      // 拿到默认的算分题的传值
      const data = yield surveyModelUtil.visibleIfChange(
        surveyInitData.gaugeData,
        surveyInitData.countData,
        surveyInitData.answer,
        surveyInitData.schema
      );

      const SurveyModelState = {
        ossInfo: result,
        ...surveyInitData,
        ...data,
        visitNumber: surveyInfo.visitNumber,
        userId: surveyInfo.userId,
        channel: surveyInfo.channel,
        answerId: payload.answerId,
        patientId: payload.patientId,
        questionId: gaugeData.id,
        isCache: surveyInitData.currentCatchIf,
        code: payload.code,
        roleAndUrl: payload.roleAndUrl,
        roleType,
      };
      yield put({
        type: 'allSave',
        payload: SurveyModelState,
      });

      if (callback) {
        callback();
      }
    },

    /**
     * form表单变化
     * @param { field } 字段名
     * @param { val } 返回值
     */
    *changeForm({ payload }, { put, select, call }) {
      const state: ISurvey = yield select(({ survey }: { survey: ISurvey }) => survey);
      if (
        JSON.stringify(state.answer[payload.props.formObj.subjectData.field]) !== JSON.stringify(payload.val)
        // payload.props.formObj.subjectData.subjectType === 'FormAloneDate'
      ) {
        const surveyModelUtil = new SurveyModelUtil();
        // 判断是复合组件还是普通组件
        const isGroup = payload.props.formObj.subjectData.parentPosition;
        // yield call(surveyModelUtil.delay, 200);
        const surveyData = yield surveyModelUtil[isGroup ? 'changeGroupSurvey' : 'changeSurvey'](payload, state);
        if (surveyData) {
          yield put({
            type: 'allSave',
            payload: {
              ...surveyData,
              isCache: state.currentCatchIf,
            },
          });
        }
      }
    },
    /**
     * 选择菜单
     * param 直接记录payload里面的参数
     * @param menuIndex 1级菜单下标
     * @param menuIChild 2级菜单下标
     */
    *selectMenu({ payload }, { put, select, call }) {
      const state = yield select(({ survey }: { survey: ISurvey }) => survey);
      const surveyModelUtil = new SurveyModelUtil();
      if (payload.menuIndex !== state.menuIndex) {
        yield put({ type: 'LoadModel/directSave', payload: { isLoading: true } });
        yield call(surveyModelUtil.delay, 0);
        yield put({
          type: `allSave`,
          payload,
        });
        return;
      }
      surveyModelUtil.scrollToWindow({ ...state, ...payload });
    },
    /**
     * 重置state
     */
    *restState({}, { put, select }) {
      const surveyModelUtil = new SurveyModelUtil();
      const state = yield surveyModelUtil.restState();
      yield put({
        type: 'allSave',
        payload: { ...state, schema: {}, answer: {}, isCache: false },
      });
    },

    /**
     * 直接保存传入的值
     */
    *directSave({ payload, callback }, { put }) {
      // console.log(payload, '我是上层数据');
      yield put({
        type: 'allSave',
        payload,
      });
      if (callback) {
        callback();
      }
    },
  },
  reducers: {
    // 全部存储方法
    // tslint:disable-next-line:no-any
    allSave(state: ISurvey, action: any) {
      if (timer) {
        clearTimeout(timer);
        timer = null;
      }
      if (action.payload.isCache) {
        timer = setTimeout(async () => {
          // 扫码进入
          if (state.code || action.payload.code) {
            await GaugeSurvey.catchQrcode({
              answerCacheJson: JSON.stringify(state.answer),
              code: state.code || action.payload.code,
            });
          } else {
            if (JSON.stringify(state.answer) !== '{}') {
              // 普通
              await GaugeSurvey.createCacheGauge({
                answerCacheJson: JSON.stringify(state.answer),
                patientId: state.patientId || action.payload.patientId,
                answerId: state.answerId || action.payload.answerId,
                questionId: state.questionId || action.payload.questionId,
              });
            }
          }
        }, 300);
      }

      return {
        ...state,
        ...action.payload,
      };
    },
  },

  subscriptions: {
    setup({ dispatch, history }) {
      history.listen(({ pathname }) => {
        if (pathname === '/GaugeSurvey') {
          dispatch({
            type: 'restState',
          });
        }
      });
    },
  },
} as Model;
